﻿(function ($) {
    var sourceGrid, mnggridid, contractpermistion, rowcommand, contractmngtemplate, _ct, popupwindow,
      Search = function () {
          $(mnggridid).data("kendoGrid").dataSource.read();
      },
      ViewDetail = function (e) {
          var MaKCP = 0;
          var vMaHD = 0;
          if (e != null) {
              e.preventDefault();
              var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
              MaKCP = dataItem.MaKCP;
              vMaHD = dataItem.MaHD;
          }
          popupwindow = $("#window");
          var wndwidth = $(window).width();
          popupwindow.kendoWindow({
              width: (wndwidth * 0.9) + "px",
              height: "600px",
              title: "Thêm/Sửa Khoán chi phí",
              content: "/KCPPopup.aspx?MaHD=" + vMaHD + "&MaKCP=" + MaKCP,
              modal: true,
              animation: false,
              center: true
          });
          popupwindow.data("kendoWindow").open().center();
      },

    DeleteKCP = function (e) {
        e.preventDefault();
        var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        var mahddelete = dataItem.MaHD;
        if (confirm("Bạn có chắc chắn muốn xóa khoán chi phí này không?")) {
            $.post("/Handlers/post.ashx", { MaKCP: mahddelete, act: "xkcp" }, function (result) {
                if (result == "success") {
                    var grid = $(mnggridid).data('kendoGrid');
                    grid.dataSource.remove(dataItem);
                    showMessage('success', "Xóa khoán chi phí thành công!");
                } else {
                    showMessage('error', "Không thể xóa khoán chi phí này!");
                }
            });
        }
    },

    onDataBound = function (arg) {
        var _grid = this;
        _grid.tbody.find('>tr').each(function () {
            var dataItem = _grid.dataItem(this);
            if (dataItem.ParentID == "" || dataItem.ParentID == null) {
                $(this).addClass('ct-root');
            } else {
                $(this).addClass('ct-child');
            }
        });
    };

    $.extend($.fn, {
        InitialKCPGrid: function (options) {
            var o = $.extend({
        }, options);
        mnggridid = this;
        contractpermistion = o.contractpermistion;
        contractmngtemplate = o.ckptemplate;
        
        //permisstion
        rowcommand = new Array();
        if (contractpermistion >= 7) {
            rowcommand.push({ name: "Delete", text: "Xóa", click: DeleteKCP });
            rowcommand.push({ name: "Detail", text: "Chi tiết", click: ViewDetail });
        }
        else {
            if (contractpermistion >= 1) {
                //co quyen xem danh sach hop dong
                rowcommand.push({ name: "Detail", text: "Chi tiết", click: ViewDetail });
            } else {
                //ko co quyen xem
                return;
            }
        }

        //end permisstion

        sourceGrid = {
            serverPaging: true,
            batch: true,
            pageSize: 20,
            schema: {
                data: function (data) {
                    if (data.d != null)
                        return data.d.source;
                    else
                        return data.d;
                },
                total: function (data) {
                    if (data.d != null)
                        return data.d.total;
                    else
                        return data.d;
                },
                model: {
                    id: "MaHD",
                    fields: {
                        STT: { editable: false, nullable: true },
                        NoiDung: { validation: { required: true} },
                        SoKCP: { validation: { required: true} },
                        Ngay: { validation: { required: false} },
                        GiaTri: { type: "number", validation: { required: false} },
                        GhiChu: { validation: { required: false} }
                    }
                }
            },
            transport: {
                read: {
                    url: "/WS/hdservice.aspx/ListKCP",
                    contentType: "application/json; charset=utf-8",
                    type: "POST"
                },
                update: {
                //                        url: "/WS/hdservice.aspx/UpdateContract",
                //                        contentType: "application/json; charset=utf-8",
                //                        type: "POST",
                //                        complete: function (e) {
                //                            showMessage('success', "Cập nhật thành công");
                //                            $(mnggridid).data("kendoGrid").dataSource.read();
                //                        },
                //                        error: function (e) {
                //                            alert('error');
                //                        }
            },
            destroy: {
                url: "/WS/hdservice.aspx/DeleteKCP",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                complete: function (e) {
                    var msg = e.responseText.toString();
                    if (msg.indexOf("failed") != -1) {
                        showMessage('error', "Không thể xóa hợp đồng này!");
                    }
                    else
                        showMessage('success', "Cập nhật thành công");
                    $(mnggridid).data("kendoGrid").dataSource.read(); //refresh grid
                },
                error: function (e) {
                    alert('error');
                }
            },
            create: {
            //                        url: "/WS/hdservice.aspx/CreateContract",
            //                        contentType: "application/json; charset=utf-8",
            //                        type: "POST",
            //                        complete: function (e) {
            //                            showMessage('success', "Cập nhật thành công");
            //                            $(mnggridid).data("kendoGrid").dataSource.read();
            //                        },
            //                        error: function (e) {
            //                            alert('error');
            //                        }
        },
        parameterMap: function (data, operation) {
            if (operation != "read") {
                if (operation == "create") {
                    return JSON.stringify({ obj: data.models, MaHD: MaHD })
                }
                return JSON.stringify({ obj: data.models })
            }
            else {
                data = $.extend({ Keyword: MaHD }, data);
                return JSON.stringify({ obj: data });
            }
        }
    }
};

var grid = $(mnggridid).kendoGrid({
    dataSource: sourceGrid,
    toolbar: kendo.template($(contractmngtemplate).html()),
    pageable: true,
    resizable: true,
    navigatable: true,
    dataBound: onDataBound,
    columns: [
                                {
                                    field: "STT", title: "STT", width: "70px", editable: false, nullable: true
                                },
                                {
                                    field: "Noidung", title: "Nội dung", width: "200px", editor: textEditorInitialize
                                },
                                {
                                    field: "SoKCP", title: "Số", width: "100px"
                                },
                                {
                                    field: "Ngay", title: "Ngày", type: "date", format: "{0:dd/MM/yyyy}", editor: columndatepicker, width: "100px"
                                },
                                {
                                    field: "GiaTri", title: "Giá trị", format: "{0:N}", width: "150px"
                                },
                                {
                                    field: "GhiChu", title: "Ghi chú", width: "200px", editor: textEditorInitialize
                                },
                                {
                                    field: "CPGK_TTTC", title: "Thực thanh, thực chi", format: "{0:N}", width: "100px"
                                },
                                {
                                    field: "CPGK_QuaCTy", title: "Chi qua công ty", format: "{0:N}", width: "100px"
                                },
                                {
                                    field: "CPGK_TKCM", title: "TKCM", format: "{0:N}", width: "100px"
                                },
                                {
                                    field: "CPGK_ThueChuyenGia", title: "Thuê chuyên gia", format: "{0:N}", width: "100px"
                                },
                                {
                                    field: "CPGK_PTMauTN", title: "Phân tích mẫu (TN)", format: "{0:N}", width: "100px"
                                },
                                {
                                    field: "CPGK_PTMauMT", title: "Phân tích mẫu (P.MT)", format: "{0:N}", width: "100px"
                                },
                                {
                                    field: "CPGK_HoaChat", title: "Hóa chất", format: "{0:N}", width: "100px"
                                },
                                {
                                    field: "CPGK_Luong", title: "Lương", format: "{0:N}", width: "100px"
                                },
                                {
                                    field: "CPGK_CPK", title: "Chi phí khác", format: "{0:N}", width: "100px"
                                },

                                { command: rowcommand,
                                    title: " ",
                                    width: "100px"
                                    //width: "80px"//(rowcommand.length == 1 ? "90px" : (rowcommand.length * 65) + "px")
                                }
                            ],
    editable: false
});
}
});
} (jQuery));